%% Histograms and Random Number Generators

web('https://en.wikipedia.org/wiki/Histogram')

%Create an array of random numbers selected from the uniform distirbution
%help rand

N=1000;
X=rand(N,1);

%Create a histogram of our 'data' 
%doc hist
figure
hist(X)
xlabel('X')
ylabel('Counts')

%Try some various options of the histogram

%By default there are 10 bins.  Use 20 bins. 
figure
hist(X,20) %
xlabel('X')
ylabel('Counts')


%Use our own bin centers. 
figure
BinCenters=(.2:.1:.8) 
hist(X,BinCenters) 
xlabel('X')
ylabel('Counts')

%Replicate the default behavior
figure
MinX=min(X);
MaxX=max(X);
NBins=10;
DeltaX=(MaxX-MinX)/NBins
XStart=MinX+DeltaX/2
XEnd=MaxX-DeltaX/2
BinCenters=linspace(XStart,XEnd,NBins)
BinCenters=(XStart:DeltaX:XEnd)
hist(X,BinCenters)
xlabel('X')
ylabel('Counts')

%Instead of getting a making a plot, get back the bin centers and counts
%and then make our own plot. 
NBins=20
[Counts,BinCenters]=hist(X,NBins)
figure
B=bar(BinCenters,Counts)
B.BarWidth=1
xlabel('X')
ylabel('Counts')

%% Normally Distributed Data

web('https://en.wikipedia.org/wiki/Normal_distribution')

%doc randn

%Create array
N=100000; %Try changing this number
X=randn(N,1);

NBins=200 %Try changing this number 

[Counts,BinCenters]=hist(X,NBins)
figure
B=bar(BinCenters,Counts)
B.BarWidth=1
xlabel('X')
ylabel('Counts')



%% Compare our data to that expected from the Gaussian Function


%Create a large amount of data
N=1000000;
X=randn(N,1);

NBins=200 %Many bins

[Counts,BinCenters]=hist(X,NBins)
DeltaX=BinCenters(2)-BinCenters(1)

%Normalize the total counts to be '1'
NormCounts=Counts/sum(Counts);

%Plot the histogram
figure
B=bar(BinCenters,NormCounts)
B.BarWidth=1
xlabel('X')
ylabel('Counts')

%Anonynmous function for the Gaussian (Normal) distribution with mean =0, sigma=1
NormDist=@(X)1/sqrt(2*pi)*exp(-X.^2/2)

%Calculate the function at the location of our bin centers 
NatBins=NormDist(BinCenters)

hold on %so that curve will go on top of existing bar graph

%We have finite width bins, so the the counts in each bin coorespond to
%that expected from the integral of our Probability Distribution Function
%(PDF) over the finite bin width.  If the bins are 'small' then the
%integral is well approximated by the function height times bin width 
%(e.i. the MidPoint method). 

plot(BinCenters,NatBins*DeltaX,'r')

%We can see the random number generator is correctly selecting numbers from
%the normal distribution with mean = 0 and sigma =1. 








